package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
)

type LoginRequest struct {
	LoginName string `json:"loginName"`
	LoginPwd  string `json:"loginPwd"`
}

func helloHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Printf("int Request\n")
	if r.Method == http.MethodGet {
		// 处理GET请求
		fmt.Printf("into Get\n")
		queryParams := r.URL.Query()
		loginName := queryParams.Get("loginName")
		loginPwd := queryParams.Get("loginPwd")
		fmt.Printf("loginName:" + loginName + "pwd:" + loginPwd)
		if loginName == "RedMudStove" && loginPwd == "5486426" {
			response := fmt.Sprintf("Hello, welcome to login! %s", loginName)
			w.Write([]byte(response))
		} else {
			w.Write([]byte("error!"))
		}
	} else if r.Method == http.MethodPost {
		// 处理POST请求
		contentType := r.Header.Get("Content-Type")
		fmt.Printf("into Post\n")
		if contentType == "application/x-www-form-urlencoded" {
			loginName := r.FormValue("loginName")
			loginPwd := r.FormValue("loginPwd")
			fmt.Printf("into Post1\n")
			if loginName == "RedMudStove" && loginPwd == "5486426" {
				response := fmt.Sprintf("Hello, welcome to login! %s", loginName)
				w.Write([]byte(response))
			} else {
				w.Write([]byte("error!"))
			}
		} else if contentType == "application/json" {
			fmt.Printf("into Post2\n")
			var loginReq LoginRequest
			err := json.NewDecoder(r.Body).Decode(&loginReq)
			if err != nil {
				http.Error(w, err.Error(), http.StatusBadRequest)
				return
			}

			fmt.Printf("loginName:" + loginReq.LoginName + "pwd:" + loginReq.LoginPwd)
			if loginReq.LoginName == "RedMudStove" && loginReq.LoginPwd == "5486426" {
				response := fmt.Sprintf("Hello, welcome to login! %s", loginReq.LoginName)
				w.Write([]byte(response))
			} else {
				w.Write([]byte("error!"))
			}
		} else {
			w.WriteHeader(http.StatusUnsupportedMediaType)
			w.Write([]byte("Unsupported Media Type"))
		}
	} else {
		// 处理其他类型的请求
		w.WriteHeader(http.StatusMethodNotAllowed)
		w.Write([]byte("Method Not Allowed"))
	}
}

func main() {
	http.HandleFunc("/", helloHandler)
	fmt.Printf("Starting server at port 80\n")
	if err := http.ListenAndServe(":80", nil); err != nil {
		log.Fatal(err)
	}
}
